<?php
/*
 * 单据打印
 */

class ome_ctl_admin_receipts_print extends desktop_controller{
    var $name = "发货中心";
    var $workground = "delivery_center";

     /*
     * 添加发货/单据打印 下的 顶部view
     */
    function _views(){
        $mdl_order = $this->app->model('delivery');
        $sub_menu = $this->getView($_GET['status']);
        $i=0;
        foreach($sub_menu as $k=>$v){
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl=admin_receipts_print&act=index&view='.$i++.'&status='.$_GET['status'].'&logi_id='.urlencode($v['filter']['logi_id']);
        }

        return $sub_menu;
    }

    function getView($status){
        $mdl_order = $this->app->model('delivery');
        $submenu = $mdl_order->getLogi_name();

        if(empty($submenu))return $submenu;

        $tmp_filter = array('type'=>'normal');
        $s_filter = $this->analyseStatus($status);
        $tmp_filter = array_merge($tmp_filter,$s_filter);

        $c = 1;
        $sub_menu[0] = array(
                'label'=>app::get('base')->_($tmp_filter['_title_']),
                'filter'=>$tmp_filter,
                'optional'=>false
        );
        $logi_ids = array();
        foreach($submenu as $keys=>$values){
            if($values['logi_id'] == ''){
              unset($values['logi_id']);
              continue;
            }
            $logi_ids[] = $values['logi_id'];
        }
        $ome_logi_names = $mdl_order->getOMELogiName($logi_ids);
        foreach($submenu as $keys=>$values){
            if(!isset($ome_logi_names[$values['logi_id']]))continue;
            $sub_menu[$c] = array(
                'label'=>app::get('base')->_($ome_logi_names[$values['logi_id']]),
                'filter'=>array_merge($tmp_filter,array('logi_id'=>$values['logi_id'])),
                'optional'=>false
            );
            $c++;
        }
        return $sub_menu;
    }

    function index(){
        $title = '';
        if(isset($_POST['delivery_bn']) && $_POST['delivery_bn']){
            $deliveryObj = &$this->app->model('delivery');
            $rows = $deliveryObj->getParentIdBybn($_POST['delivery_bn']);
            if($rows){
                foreach($rows as $val){
                    $deliveryId[] = $val['parent_id'];
                }
                $filter['extend_delivery_id'] = $deliveryId;
            }
        }
        $filter['type'] = 'normal';
        $status_cfg = $this->app->getConf('ome.delivery.status.cfg');
        //分析status的filter条件
        $tmp_filter = $this->analyseStatus($_GET['status']);
        $filter = array_merge($filter,$tmp_filter);

        /*
         * 获取操作员管辖仓库
         */
        $oBranch = &app::get('ome')->model('branch');
        $is_super = kernel::single('desktop_user')->is_super();
        if (!$is_super){
           $branch_ids = $oBranch->getBranchByUser(true);
           if ($branch_ids){
                $filter['branch_id'] = $branch_ids;
           }else{
                $filter['branch_id'] = 'false';
           }
        }
        $attach = '&status='.$_GET['status'].'&logi_id='.$_GET['logi_id'];
        $params = array(
                        'title'=>$filter['_title_'],
                        'actions' => array(
                                'stock' => array(
                                    'label' => '打印备货单',
                                    'submit' => 'index.php?app=ome&ctl=admin_receipts_print&act=toPrintStock'.$attach,
                                    'target' => "_blank",
                                ),
                                'delie' => array(
                                    'label' => '打印发货单',
                                    'submit' => 'index.php?app=ome&ctl=admin_receipts_print&act=toPrintMerge'.$attach,
                                    'target' => '_blank',
                                ),
                                'expre' => array(
                                    'label' => '打印快递单',
                                    'submit' => 'index.php?app=ome&ctl=admin_receipts_print&act=toPrintShip'.$attach,
                                    'target' => '_blank',//"dialog::{width:800,height:600,title:'设置标签'}",//
                                ),
                                /*'unite' => array(
                                    'label' => '联合打印',
                                    'submit' => 'index.php?app=ome&ctl=admin_receipts_print&act=toMergePrint'.$attach,
                                    'target' => '_blank',//dialog::{width:800,height:600,title:'设置标签'}",//
                                ),*/
 
                               array(
                                   'label' => '导出全部',
                                   'href' => 'index.php?app=omedlyexport&ctl=ome_delivery&act=index&action=export&type=all',
                                   'target' => "dialog::{width:400,height:170,title:'导出全部'}",
                               ),
                                'style' => array(
                                    'label' => '打印样式',
                                    'href' => 'index.php?app=ome&ctl=admin_receipts_print&act=showPrintStyle',
                                    'target'=>'dialog::{width:1000,height:400,title:\'打印样式\'}'
                                ),
                        ),
                        'base_filter' => $filter,
                        'use_buildin_new_dialog' => false,
                        'use_buildin_set_tag'=>false,
                        'use_buildin_recycle'=>false,
                        'use_buildin_export'=>false,
                        'use_buildin_import'=>false,
                        'use_buildin_filter'=>true,
                        'max_actions'=>8,
                        'use_view_tab'=>true,
                        //从载方法 以解决 发货中未录入快递单号不能过滤的bug
                        'object_method'=>array('count'=>'count_logi_no','getlist'=>'getlist_logi_no'),
                    );
                    //选择显示打印的按钮
        if($status_cfg != ''){
		        if($status_cfg['set']['stock'] == 0){
		            unset($params['actions']['stock']);
		        }
		        if($status_cfg['set']['delie'] == 0){
		            unset($params['actions']['delie']);
		        }
        }
        //暂停列表不显示按钮
        if($_GET['status'] == 6){
        	unset($params['actions']['stock']);
        	unset($params['actions']['delie']);
        	unset($params['actions']['style']);
        	unset($params['actions']['expre']);
        }

        $this->finder('ome_mdl_delivery', $params);
    }
    
    /**
     * 代销售
     */
    function supply(){
    	$title = '';
    	if(isset($_POST['delivery_bn']) && $_POST['delivery_bn']){
    		$deliveryObj = &$this->app->model('delivery');
    		$rows = $deliveryObj->getParentIdBybn($_POST['delivery_bn']);
    		if($rows){
    			foreach($rows as $val){
    				$deliveryId[] = $val['parent_id'];
    			}
    			$filter['extend_delivery_id'] = $deliveryId;
    		}
    	}
    	$filter['type'] = 'supply';
    	$status_cfg = $this->app->getConf('ome.delivery.status.cfg');
    	//分析status的filter条件
    	$tmp_filter = $this->analyseStatus($_GET['status']);
    	$filter = array_merge($filter,$tmp_filter);
    
    	/*
    	 * 获取操作员管辖仓库
    	*/
    	$oBranch = &app::get('ome')->model('branch');
    	$is_super = kernel::single('desktop_user')->is_super();
    	if (!$is_super){
    		$branch_ids = $oBranch->getBranchByUser(true);
    		if ($branch_ids){
    			$filter['branch_id'] = $branch_ids;
    		}else{
    			$filter['branch_id'] = 'false';
    		}
    	}
    	$attach = '&status='.$_GET['status'].'&logi_id='.$_GET['logi_id'];
    	$params = array(
    			'title'=>$filter['_title_'],
    	
    			
    			'base_filter' => $filter,
    			'use_buildin_new_dialog' => false,
    			'use_buildin_set_tag'=>false,
    			'use_buildin_recycle'=>false,
    			'use_buildin_export'=>false,
    			'use_buildin_import'=>false,
    			'use_buildin_filter'=>true,
    			'max_actions'=>8,
    			'use_view_tab'=>true,
    			//从载方法 以解决 发货中未录入快递单号不能过滤的bug
    			'object_method'=>array('count'=>'count_logi_no','getlist'=>'getlist_logi_no'),
    	);
    
    
    	$this->finder('ome_mdl_delivery', $params);
    }
    /*
     * 分析状态
     */
    function analyseStatus($status, $type='normal'){
    	$status_cfg = $this->app->getConf('ome.delivery.status.cfg');
        if ($type == 'normal'){
        switch ($status){
            case '':
                $title = '全部';
                $filter = array();
                $filter['pause'] = "FALSE";
                break;
            case 0:
                $title = '待打印';
                if($status_cfg != ''){
                    if(($status_cfg['set']['stock'] == 1 && $status_cfg['set']['delie'] == 1) ){
                        $filter['todo'] = "1";
                        $filter['pause'] = "FALSE";
                        $filter['verify'] = 'FALSE';
                        $filter['process'] = "FALSE";
                    }
                    if($status_cfg['set']['stock'] == 1 && $status_cfg['set']['delie'] == 0){
                        $filter['todo'] = "2";
                        $filter['pause'] = "FALSE";
                        $filter['verify'] = 'FALSE';
                        $filter['process'] = "FALSE";
                    }
                    if($status_cfg['set']['stock'] == 0 && $status_cfg['set']['delie'] == 1){
                        $filter['todo'] = "3";
                        $filter['pause'] = "FALSE";
                        $filter['verify'] = 'FALSE';
                        $filter['process'] = "FALSE";
                    }
                    if($status_cfg['set']['stock'] == 0 && $status_cfg['set']['delie'] == 0 ){
                         $filter['todo'] = "4";
                         $filter['pause'] = "FALSE";
                         $filter['verify'] = 'FALSE';
                         $filter['process'] = "FALSE";
                    }
                }else{
                    $filter['todo'] = "1";
                    $filter['pause'] = "FALSE";
                    $filter['verify'] = 'FALSE';
                    $filter['process'] = "FALSE";
                }
                break;
            case 1:
                $title = '已打印';
                if($status_cfg != ''){
	                if(($status_cfg['set']['stock'] == 1 && $status_cfg['set']['delie'] == 1) ){
	                    $filter['stock_status'] = "TRUE";
	                    $filter['deliv_status'] = "TRUE";
	                    $filter['expre_status'] = "TRUE";
	                    $filter['pause'] = "FALSE";
	                    $filter['verify'] = 'FALSE';
                        $filter['process'] = "FALSE";
	                }
	                if($status_cfg['set']['stock'] == 1 && $status_cfg['set']['delie'] == 0){
	                    $filter['expre_status'] = "TRUE";
	                    $filter['stock_status'] = "TRUE";
	                    $filter['pause'] = "FALSE";
	                    $filter['verify'] = 'FALSE';
                        $filter['process'] = "FALSE";
	                }
			        if($status_cfg['set']['stock'] == 0 && $status_cfg['set']['delie'] == 1){
			            $filter['expre_status'] = "TRUE";
			            $filter['deliv_status'] = "TRUE";
			            $filter['pause'] = "FALSE";
			            $filter['verify'] = 'FALSE';
                        $filter['process'] = "FALSE";
			        }
			        if($status_cfg['set']['stock'] == 0 && $status_cfg['set']['delie'] == 0 ){
			             $filter['expre_status'] = "TRUE";
			             $filter['pause'] = "FALSE";
			             $filter['verify'] = 'FALSE';
                         $filter['process'] = "FALSE";
			        }
                }else{
                	$filter['stock_status'] = "TRUE";
                    $filter['deliv_status'] = "TRUE";
                    $filter['expre_status'] = "TRUE";
                    $filter['pause'] = "FALSE";
                    $filter['verify'] = 'FALSE';
                    $filter['process'] = "FALSE";
                }
                break;
            case 2:
                $title = '未录入物流单号';
                $filter['logi_no'] = 'NULL';
                $filter['pause'] = "FALSE";
                break;
            case 3:
                $title = '已校验';
                $filter['verify'] = 'TRUE';
                $filter['process'] = "FALSE";
                $filter['pause'] = "FALSE";
                break;
            case 4:
                $title = '未发货';
                $filter['process'] = "FALSE";
                $filter['pause'] = "FALSE";
                break;
            case 5:
                $title = '已发货';
                $filter['process'] = "TRUE";
                $filter['pause'] = "FALSE";
                break;
            case 6:
                $title = '暂停列表';
                $filter['pause'] = "TRUE";
                break;
        }
        }elseif ($type == 'refunded'){
            switch ($status){
                case '':
                    $title = '未发货';
                    $filter['process'] = "FALSE";
                    $filter['pause'] = "FALSE";
                    break;
                case 1:
                    $title = '未发货';
                    $filter['process'] = "FALSE";
                    $filter['pause'] = "FALSE";
                    break;
                case 2:
                    $title = '已发货';
                    $filter['process'] = "TRUE";
                    $filter['pause'] = "FALSE";
                    break;
            }
        }
        //默认条件
        $filter['parent_id'] = 0;
        $filter['disabled'] = 'false';
        $filter['status'] = array('ready','progress','succ');
        $filter['_title_'] = $title;

        return $filter;
    }

    function processFilter(){
        //来源于
        if ($_GET['from'] && $_GET['from'] == 'refunded'){
            //原样寄回
            $filter['type'] = 'reject';
            //TODO 可能通过getView()方法实现 （待升到1.3 moontools）
            $tmp = $this->analyseStatus($_GET['status'],'refunded');//判断为哪种列表
            $filter = array_merge($filter, $tmp);
        }else{
            //正常发货
            $filter['type'] = 'normal';
            //TODO 可能通过getView()方法实现 （待升到1.3 moontools）
            $tmp = $this->analyseStatus($_GET['status']);//判断为哪种列表
            $filter = array_merge($filter, $tmp);
        }
        //解析 view条件
        if ($_GET['logi_id']){
            $filter['logi_id'] = urldecode($_GET['logi_id']);
        }
        /*
         * 可扩展条件
         */

        return $filter;
    }

    /*
     * 处理发货单ID
     */
    function processDeliveryId(){
        $delivery_ids = $_POST['delivery_id'];
        $isSelectAll  = $_POST['isSelectedAll'];
        $filter = $this->processFilter();

        $printShip = false;
        $logi = array();
        if ($_GET['act'] == 'toPrintShip'){
            $printShip = true;
        }
        $dlyObj = &$this->app->model('delivery');
        if ($isSelectAll == '_ALL_'){
            //所有数据
            $ids = $dlyObj->getList('delivery_id,logi_id', $filter, 0, -1);
            $dly_ids = array();
            if ($ids){
                foreach ($ids as $id){
                    if ($printShip) $logi[$id['logi_id']]++;
                    $this->checkOrderStatus($id['delivery_id']);
                    $dly_ids[] = $id['delivery_id'];
                }
                if (count($logi) > 1) exit("当前系统不支持同时打印二种不同快递类型的单据，请重新选择后再试。");
                return $dly_ids;
            }
            exit("无数据");
        }else {
            $delivery_ids = array_filter($delivery_ids);//去除值 为空，null，FALSE的key和value
            //选择的数据
            if ($delivery_ids){
                if (is_array($delivery_ids)){
                    $filter_['delivery_id'] = $delivery_ids;
                    $ids = $dlyObj->getList('delivery_id,logi_id', $filter_, 0, -1);
                    $dly_ids = array();
                    if ($ids){
                        foreach ($ids as $id) {
                            if ($printShip) $logi[$id['logi_id']]++;
                            $this->checkOrderStatus($id['delivery_id']);
                            $dly_ids[] = $id['delivery_id'];
                        }
                        if (count($logi) > 1) exit("当前系统不支持同时打印二种不同快递类型的单据，请重新选择后再试。");
                        return $dly_ids;
                    }
                    exit("无数据");
                }else {
                    $this->checkOrderStatus($delivery_ids);
                    return array($delivery_ids);
                }
            }else {
                exit("请选择数据");
            }
        }
    }

    /*
     * 联合打印
     */

    function toMergePrint(){
        $total = 0;
        $_err = 'false';
        $ids = $this->processDeliveryId();

		//批次号 by sy
        $idents = $this->_getPrintQueue($ids);
		$idsAll = $this->parsePrintIds($ids);
        $allItems = array();


        $items = array();
        if ($ids){
            sort($ids);
            foreach ($ids as $id){
                $dlyObj = &$this->app->model('delivery');
                $orderObj = &$this->app->model('orders');
                //$dly_ipObj = &$this->app->model('dly_items_pos');
                //$branch_pObj = &$this->app->model('branch_pos');
                $pObj = &$this->app->model('products');
                $oiObj = &$this->app->model('order_items');
                $odObj = &$this->app->model('delivery_order');
                $diObj = &$this->app->model('delivery_items');
                $data = $dlyObj->dump($id,'*',array('delivery_items'=>array('*'),'delivery_order'=>array('*')));
                if ($data['parent_id'] != 0){
                    $_err = 'true';
                    continue;
                }
                if ($data){
					 //批次号
                    $allItems[$data['delivery_id']] = $data;

                    foreach ($data['delivery_items'] as $k => $v){
                        //取消打印验证
//                        $re = $dlyObj->existStockIsPlus($v['product_id'],$v['number'],$v['item_id'],$data['branch_id'],$err,$v['bn']);
//                        if (!$re){
//                            exit($err);
//                        }
                        $total += $v['number'];
                        /*$dip_data = $dly_ipObj->getList('pos_id,num',array('item_id'=>$v['item_id']), 0, -1);
                        foreach ($dip_data as $it){
                           $bp = $branch_pObj->dump($it['pos_id'],'store_position');
                           $tmpp['store_position'] = $bp['store_position'];
                           $tmpp['num'] = $it['num'];
                           $data['delivery_items'][$k]['pos'][] = $tmpp;
                        }*/
//                        $p = $pObj->dump($v['product_id']);
//                        $data['delivery_items'][$k]['spec_info'] = $p['spec_info'];
//                        $data['delivery_items'][$k]['name'] = $p['name'];
//                        $data['delivery_items'][$k]['addon'] = $p['spec_info'];
                        $delivery_id = $v['delivery_id'];
                       //根据配置 by sy
					    $status_cfg = $this->app->getConf('ome.delivery.status.cfg');
						$is_print_front = false;
						if($status_cfg && $status_cfg['set']['ome_delivery_merge_print'] ==1 ){
							$is_print_front = true;
						}
                        if($is_print_front){
                             //如果是合并的发货单，取得子发货单对应的order_id 以取得addon（显示前台的规格跟名称）
                            if($dlyObj->existIsMerge_parent($v['delivery_id'])){
                            	$row = $dlyObj->getItemsByParentId($v['delivery_id']);
                            	$dly_id = explode(',', $row);
                                foreach($dly_id as $id_v){
                                    $product_id = $diObj->getList('product_id',array('delivery_id'=>$id_v),0,-1);
                                    foreach($product_id as $key => $value){
                                        if($v['product_id'] == $value['product_id']){
                                            $order_id = $odObj->dump(array('delivery_id'=>$id_v),'order_id');
                                            $arr = $oiObj->dump(array('product_id'=>$v['product_id'],'order_id'=>$order_id['order_id']),'name,addon');
                                            $addon = ome_order_func::format_order_items_addon($arr['addon']);
                                        }
                                    }
                                }
                                $data['delivery_items'][$k]['name'] = $arr['name'];
                                $data['delivery_items'][$k]['addon'] = $addon;

                            }else{
                            	$order_id = $odObj->dump(array('delivery_id'=>$v['delivery_id']),'order_id');
                                $arr = $oiObj->dump(array('product_id'=>$v['product_id'],'order_id'=>$order_id),'name,addon');
                                $data['delivery_items'][$k]['name'] = $arr['name'];
                                $addon = ome_order_func::format_order_items_addon($arr['addon']);
                                $data['delivery_items'][$k]['addon'] = $addon;
                            }
                        }else{
                            $p = $pObj->dump($v['product_id']);
                            $data['delivery_items'][$k]['spec_info'] = $p['spec_info'];
                            $data['delivery_items'][$k]['name'] = $p['name'];
                            $data['delivery_items'][$k]['product_name'] = $p['name'];
                            $data['delivery_items'][$k]['addon'] = $p['spec_info'];
                        }
                    }
                    $tmp = $this->app->model('members')->dump($data['member_id'],'uname,name,mobile,tel');
                    $data['member_name'] = $tmp['account']['uname'];
                    $t_tel = array();
                    if($tmp['contact']['phone']['telephone']){
                        $t_tel[] = $tmp['contact']['phone']['telephone'];
                    }
                    if($tmp['contact']['phone']['mobile']){
                        $t_tel[] = $tmp['contact']['phone']['mobile'];
                    }
                    $order_bn = array();
                    if ($data['delivery_order'])
                    foreach ($data['delivery_order'] as $v)
                    {
                        $order = $orderObj->dump($v['order_id'],'order_bn,custom_mark,mark_text');
                        if ($order['custom_mark']){
                            $mark = unserialize($order['custom_mark']);
                            if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im){
                                $data['_mark'][$order['order_bn']][] = $im;
                            }
                        }

                        if ($order['mark_text']){
                            $mark = unserialize($order['mark_text']);
                            if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im){
                                $data['_mark_text'][$order['order_bn']][] = $im;
                            }
                        }

                        $order_bn[] = $order['order_bn'];
                    }
                    $data['order_bn'] = implode(" , ",$order_bn);
                    if ($t_tel) $data['member_tel'] = implode(" / ",$t_tel);
                    $items[] = $data;
                    $this->checkOrderStatus($id);
                }else {
                    $_err = 'true';
                }
            }
        }
        if ($ids) $vid = implode(',', $ids);
        foreach($items as $k=>$rows){
            $delivery_total_nums = 0;
            foreach($rows['delivery_items'] as $item_k=>$v){
                $delivery_total_nums += $v['number'];
            }
            $rows['delivery_total_nums'] = $delivery_total_nums;
            $rows['order_total_amount'] = $dlyObj->getAllTotalAmountByDelivery($rows['delivery_order']);
            $items[$k] = $rows;
        }
        $this->pagedata['err'] = $_err;
        $this->pagedata['vid']  = $vid;

		  //批次号
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];


        $this->pagedata['items']= $items;
        $this->pagedata['total']= $total;
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['time'] = date("Y-m-d H:i:s");
        $this->pagedata['title'] = '联合打印单打印';

        $this->_systmpl = &$this->app->model('print_tmpl_diy');
        $this->_systmpl->singlepage('ome','admin/delivery/merge_print',$this->pagedata);
        $this->display('admin/delivery/print.html');
    }

    /**
     *打印发货单
     *
     */
    function toPrintMerge(){
        $_err = 'false';
        $ids = $this->processDeliveryId();

		//批次号 by sy
        $idents = $this->_getPrintQueue($ids);
		$idsAll = $this->parsePrintIds($ids);
        $allItems = array();
        if ($ids){
            sort($ids);
            $dlyObj = &$this->app->model('delivery');
            $orderObj = &$this->app->model('orders');
            $pObj = &$this->app->model('products');
            $bppObj = &$this->app->model('branch_product_pos');
            $didObj = &$this->app->model('delivery_items_detail');
            foreach ($ids as $id){
                $data = $dlyObj->dump($id,'*',array('delivery_items'=>array('*'),'delivery_order'=>array('*')));
                if ($data['parent_id'] != 0){
                    $_err = 'true';
                    continue;
                }
                if ($data){
					 //批次号
                    $allItems[$data['delivery_id']] = $data;
                    $shop = $dlyObj->getShopInfo($data['shop_id']);
                    $data['shop_name'] = $shop['name'];
                    foreach ($data['delivery_items'] as $k => $item){
//                        $re = $dlyObj->existStockIsPlus($item['product_id'],$item['number'],$item['item_id'],$data['branch_id'],$err,$item['bn']);
//                        if (!$re){
//                            exit($err);
//                        }
                        $didArr = $didObj->dump(array('delivery_id'=>$item['delivery_id'],'delivery_item_id'=>$item['item_id']));
                        $p = $pObj->dump($item['product_id']);
                        $store_position = $bppObj->get_product_pos($item['product_id'],$data['branch_id']);
                        $data['delivery_items'][$k]['spec_info'] = $p['spec_info'];
                        $data['delivery_items'][$k]['name'] = $p['name'];
                        $data['delivery_items'][$k]['store_position'] = $store_position;
                        $data['delivery_items'][$k]['addon'] = $p['spec_info'];
                        $data['delivery_items'][$k]['price'] = $didArr['price'];
                        $data['order_cost_item'] += $didArr['amount'];
                    }

                    $tmp = $this->app->model('members')->dump($data['member_id'],'uname,name,mobile,tel');
                    $data['member_name'] = $tmp['account']['uname'];
                    $t_tel = array();
                    if($tmp['contact']['phone']['telephone']){
                        $t_tel[] = $tmp['contact']['phone']['telephone'];
                    }
                    if($tmp['contact']['phone']['mobile']){
                        $t_tel[] = $tmp['contact']['phone']['mobile'];
                    }
                    $order_bn = array();
                    if ($data['delivery_order'])
                    foreach ($data['delivery_order'] as $v){
                        $order = $orderObj->dump($v['order_id'],'order_bn,custom_mark,mark_text,is_tax,tax_no,tax_company,cost_freight');
                         
                        //不是合并发货单取订单的前端物流费用
                        if(count($data['delivery_order']) == 1){
                        	$data['front_cost_freight'] = $order['shipping']['cost_shipping'];
                        }
                        
                        if ($order['custom_mark']){
                            $mark = unserialize($order['custom_mark']);
                            if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im){
                                $data['_mark'][$order['order_bn']][] = $im;
                            }
                        }

                        if ($order['mark_text']){
                            $mark = unserialize($order['mark_text']);
                            if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im){
                                $data['_mark_text'][$order['order_bn']][] = $im;
                            }
                        }
                        
                        if ($order['is_tax']){
                        	$tax = $order['is_tax'];
                        	if($tax){ 
                        		$data['tax'][$order['order_bn']]['is_tax']= $order['is_tax'];
                        		$data['tax'][$order['order_bn']]['tax_no']= $order['tax_no'];
                        		$data['tax'][$order['order_bn']]['tax_company']= $order['tax_title'];
                        		 
                        	}
                        }

                        $order_bn[] = $order['order_bn'];
                    }
                     
                    $data['order_bn'] = implode(" , ",$order_bn);
                    if ($t_tel) $data['member_tel'] = implode(" / ",$t_tel);
                    $items[] = $data;
                    $this->checkOrderStatus($id);
                }else {
                    $_err = 'true';
                }
            }
        }

        function cmp($a, $b){
            return strcmp($a["store_position"], $b["store_position"]);
        }
        
        $status_cfg = $this->app->getConf('ome.delivery.status.cfg');
		$is_print_front = false;
		if($status_cfg && $status_cfg['set']['ome_delivery_is_printdelivery'] == 1){
			$is_print_front = true;
		}

     	foreach($items as $k=>$item){
        	usort($item['delivery_items'], "cmp");
        	
     	    if(!$is_print_front) {
            	foreach($item['delivery_items'] as $i => $di) {
            	    $item['delivery_items'][$i]['product_name'] = $di['name'];
            	}
        	}
        	
        	$items[$k] = $item;
        }


		 //商品名称和规格取前台,是合并发货单,取第一个订单的货品名称
        if($ids && $is_print_front){
            $arrPrintProductName = $dlyObj->getPrintProductName($ids);
            if(!empty($arrPrintProductName)){
                foreach($items as $k=>$rows){
                    foreach($rows['delivery_items'] as $k2=>$v){
                        $rows['delivery_items'][$k2]['product_name'] = $arrPrintProductName[$v['bn']]['name'];
                        $rows['delivery_items'][$k2]['store_position'] = $arrPrintProductName[$v['bn']]['store_position'];
                        $rows['delivery_items'][$k2]['name'] = $arrPrintProductName[$v['bn']]['name'];
                        $rows['delivery_items'][$k2]['addon'] = $arrPrintProductName[$v['bn']]['addon'];
                        $rows['delivery_items'][$k2]['spec_info'] = $arrPrintProductName[$v['bn']]['addon'];
                    }
                    $items[$k] = $rows;
                }
            }
        }

        if ($ids) $vid = implode(',', $ids);
        $oiObj = &$this->app->model('order_items');
        foreach($items as $k=>$rows){
            $delivery_total_nums = 0;
            foreach($rows['delivery_items'] as $v){
                $delivery_total_nums += $v['number'];
                /*$item_id = $v['item_id'];
                $arr = $oiObj->dump($v['item_id'],'name,addon');
                $rows['delivery_items'][$v['item_id']]['name'] = $arr['name'];
                $addon = ome_order_func::format_order_items_addon($arr['addon']);
                $rows['delivery_items'][$v['item_id']]['addon'] = $addon;*/
            }
            $rows['delivery_total_nums'] = $delivery_total_nums;
            $rows['order_total_amount'] = $dlyObj->getAllTotalAmountByDelivery($rows['delivery_order']);
            $items[$k] = $rows;
        }

        $this->pagedata['err'] = $_err;
        $this->pagedata['vid']  = $vid;

		 //批次号
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];

 
        $this->pagedata['items']= $items;
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['time'] = date("Y-m-d H:i:s");
        $this->pagedata['title'] = '发货单打印';

        $this->_systmpl = &$this->app->model('print_tmpl_diy');
        $this->_systmpl->singlepage('ome','admin/delivery/delivery_print',$this->pagedata);
        $this->display('admin/delivery/print.html');
    }

    /**
     * 打印快递单
     *
     */
    function toPrintShip(){
        $dlyObj = &$this->app->model('delivery');
        
        $orderObj = &$this->app->model('orders');
        $dly_corpObj = &$this->app->model('dly_corp');
		$pObj = &$this->app->model('products');
        $order_sellagentObj = &$this->app->model('order_selling_agent');
        $_err = 'false';

        $ids = $this->processDeliveryId();

		//批次号 by sy
        $idents = $this->_getPrintQueue($ids);
		$idsAll = $this->parsePrintIds($ids);
        $allItems = array();

        $express_company_no = '';
        if ($ids){
            sort($ids);
            $idds = $ids;
            unset($ids);
            $rows = array();
            foreach ($idds as $id){
                $data = $dlyObj->dump($id,'*',array('delivery_order'=>array('*'),'delivery_items'=>array('*')));
                if ($data['parent_id'] != 0){
                    $_err = 'true';
                    continue;
                }
                $num = 0;
                $err='';
                if ($data){
					  //批次号
                    $allItems[$data['delivery_id']] = $data;


                    foreach ($data['delivery_items'] as  $k=>$i){
//                        $re = $dlyObj->existStockIsPlus($i['product_id'],$i['number'],$i['item_id'],$data['branch_id'],$err,$i['bn']);
//                        if (!$re){
//                            exit($err);
//                        }
                        $num += $i['number'];
						$p = $pObj->dump($i['product_id']);
                        $data['delivery_items'][$k]['product_name'] = $p['name'];
                    }
                    $o_bn = array();
                    $mark_text = array();
                    foreach ($data['delivery_order'] as $v){
                        $order = $orderObj->dump($v['order_id'],'order_bn,mark_text');

                        if ($order['mark_text']){
                            $mark = unserialize($order['mark_text']);
                            if (is_array($mark) || !empty($mark))
                            foreach ($mark as $im){
                                $mark_text[] = $im['op_content'];
                            }
                        }
                        $o_bn[] = $order['order_bn'];
                    }
                    $shop = $dlyObj->getShopInfo($data['shop_id']);
                    //发货人信息
                    $shipper_detail = $orderObj->dump(array('order_id'=>$v['order_id']),'consigner_name,consigner_area,consigner_addr,consigner_zip,consigner_email,consigner_mobile,consigner_tel');
                    /*if ($shipper_detail){
                        $shop['area'] = $shipper_detail['consigner']['area'];
                        $shop['zip'] = $shipper_detail['consigner']['zip'];
                        if ($shipper_detail['consigner']['email']){
                            $selling_detail = $order_sellagentObj->dump(array('order_id'=>$v['order_id']), 'website_name');
                            $shop['name'] = $selling_detail['website']['name'];
                        }
                        $shop['default_sender'] = $shipper_detail['consigner']['name'];
                        $shipper_area = $shipper_detail['consigner']['area'];
                        kernel::single('ome_func')->split_area($shipper_area);
                        $shop['addr'] = $shipper_area[0].$shipper_area[1].$shipper_area[2].$shipper_detail['consigner']['addr'];
                        $shop['mobile'] = $shipper_detail['consigner']['mobile'];
                        $shop['tel'] = $shipper_detail['consigner']['tel'];
                    }*/
                    $row = $dly_corpObj->dump($data['logi_id'], 'prt_tmpl_id,type');
                    $data['prt_tmpl_id'] = $row['prt_tmpl_id'];
                    $data['shopinfo']    = $shop;
                    $data['order_memo']  = implode(',', $mark_text);
                    $data['order_count'] = $num;
                    $data['order_bn']    = implode(',', $o_bn);
                    
                     
                    $data['delivery_amount'] = $dlyObj->getAllTotalAmountByDelivery($data['delivery_order']);
                    
                    //快递公式
                    if (!$express_company_no){
                        $express_company_no = strtoupper($row['type']);
                    }
                    $rows['delivery'][]  = $data;
                    $itm['delivery_id']  = $id;
                    $itm['delivery_bn']  = $data['delivery_bn'];
                    $idd[] = $itm;
                    $logid[$id] = $data['logi_no'];
                    $ids[] = $id;
                    $this->checkOrderStatus($id);
                }else {
                    $_err = 'true';
                }
            }
            if ($ids) $name = implode(',', $ids);
        }

        $rows['dly_tmpl_id']  = $data['prt_tmpl_id'];
        $rows['order_number'] = count($ids);
        $rows['name']         = $name;

		 //商品名称和规格取前台,是合并发货单,取第一个订单的货品名称
		$status_cfg = $this->app->getConf('ome.delivery.status.cfg');
		$is_print_front = false;
		if($status_cfg && $status_cfg['set']['ome_delivery_is_printship'] == 1){
			$is_print_front = true;
		}
        if($ids && $is_print_front){
            $arrPrintProductName = $dlyObj->getPrintProductName($ids);
            if(!empty($arrPrintProductName)){
                foreach($rows['delivery'] as $k=>$row){
                    foreach($row['delivery_items'] as $k2=>$v){
                        $row['delivery_items'][$k2]['product_name'] = $arrPrintProductName[$v['bn']]['name'];
                        //$row['delivery_items'][$k2]['name'] = $arrPrintProductName[$v['bn']]['name'];
                        $row['delivery_items'][$k2]['addon'] = $arrPrintProductName[$v['bn']]['addon'];
                        $row['delivery_items'][$k2]['spec_info'] = $arrPrintProductName[$v['bn']]['addon'];
                    }
                    $rows['delivery'][$k] = $row;
                }
            }
        }

        if ($rows['delivery'])
        foreach ($rows['delivery'] as $val) {
            //获取快递单打印模板的servivce定义
            $data = array();
            foreach(kernel::servicelist('ome.service.template') as $object=>$instance){
                if (method_exists($instance, 'getElementContent')){
                    $tmp = $instance->getElementContent($val);
                }
                $data = array_merge($data, $tmp);
            }
            $mydata[] = $data;
        }

        //$xmltool = &$this->app->model('utility_xml');
        $printTmpl = &$this->app->model('print_tmpl');

        $this->pagedata['data'] = addslashes($dlyObj->array2xml2($mydata,'data'));
        $this->pagedata['order_number'] = $rows['order_number'];
        $this->pagedata['prt_tmpl'] = $printTmpl->dump($rows['dly_tmpl_id'],'prt_tmpl_width,prt_tmpl_offsety,prt_tmpl_offsetx,prt_tmpl_height,prt_tmpl_data,file_id');
          /*修改的地方*/
        if($this->pagedata['prt_tmpl']['file_id']){
            $this->pagedata['tmpl_bg'] = 'index.php?app=ome&ctl=admin_delivery_print&act=showPicture&p[0]='.$this->pagedata['prt_tmpl']['file_id'];
        }
        $this->pagedata['err'] = $_err;
        $this->pagedata['vid']=$rows['name'];

		//批次号
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];
		$items = array();
        foreach($rows['delivery'] as $row){
            $items[$row['delivery_id']] = $row;
        }
        $this->pagedata['items'] = $items;

        $this->pagedata['dpi'] = 96;
        $this->pagedata['count'] = sizeof($ids);
        $this->pagedata['ids'] = $ids;
        $this->pagedata['idd'] = $idd;
        $this->pagedata['logid'] = $logid;
        $this->pagedata['express_company_no'] = $express_company_no;
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['title'] = '快递单打印';
        $this->singlepage("admin/delivery/express_print.html");
    }

    /**
     * 更新发货单的打印状态
     *
     * @param string $type
     * @param int $dly_id
     *
     */
    function setPrintStatus(){
        $type = $_POST['type'];
        $str_id = $_POST['str'];
        $dlyObj     = &$this->app->model('delivery');
        $tmp_id = explode(',', $str_id);

		if($this->_checkPrintQueue($tmp_id,$msg)){
			//$queueObj = kernel::single('ome_queue');
			//$queueObj->addPrintQueue($tmp_id);
		}else{
			echo $msg;
			exit;
		}

		$tmp_id = array_filter($tmp_id);
        $dlys   = $dlyObj->getList('*',array('delivery_id'=>$tmp_id),0,-1);
        $dly = array();
        foreach ($dlys as $k => $delivery){
            $arr_s = array('cancel', 'back', 'stop');
            if (in_array($delivery['status'], $arr_s)) continue;
            if ($delivery['status'] == 'ready') $dly[$k]['status'] = 'progress';
            $dly[$k]['delivery_id'] = $delivery['delivery_id'];
            $send_flag = false;
            switch ($type){
                case 'express':
                    if ($delivery['expre_status'] == 'false'){
                        $send_flag = true;
                    }
                    $dly[$k]['expre_status'] = 'true';
                    $dly[$k]['_log_'] = 'delivery_expre@ome';
                    $dly[$k]['_memo_'] = '快递单打印';
                    break;
                case 'stock':
                    if ($delivery['stock_status'] == 'false'){
                        $send_flag = true;
                    }
                    $dly[$k]['stock_status'] = 'true';
                    $dly[$k]['_log_'] = 'delivery_stock@ome';
                    $dly[$k]['_memo_'] = '备货单打印';
                    break;
                case 'delivery':
                    if ($delivery['deliv_status'] == 'false'){
                        $send_flag = true;
                    }
                    $dly[$k]['deliv_status'] = 'true';
                    $dly[$k]['_log_'] = 'delivery_deliv@ome';
                    $dly[$k]['_memo_'] = '发货单商品信息打印';
                    break;
                case 'stock_dly':
                    if ($delivery['deliv_status'] == 'false' && $delivery['stock_status']){
                        $send_flag = true;
                    }
                    $dly[$k]['deliv_status'] = 'true';
                    $dly[$k]['stock_status'] = 'true';
                    $dly[$k]['_isMerge_'] = true;
                    $dly[$k]['_log_'][0] = 'delivery_deliv@ome';
                    $dly[$k]['_log_'][1] = 'delivery_stock@ome';
                    $dly[$k]['_memo_'][0] = '发货单商品信息打印';
                    $dly[$k]['_memo_'][1] = '备货单打印';
                    break;
            }
            //if ($this->checkOrderStatus($delivery['delivery_id']))
            //    exit($delivery['delivery_bn'].':发货单无效');
        }
        $opObj  = &$this->app->model('operation_log');
        foreach ($dly as $k => $v){
            $_dly = $v;
            $dlyObj->save($_dly);
            
            $delivery  = $dlyObj->dump($v['delivery_id'], 'expre_status,stock_status,deliv_status');
            $status_cfg = $this->app->getConf('ome.delivery.status.cfg');
            if($status_cfg['set']['stock'] == 0){
            	$delivery['stock_status']='true';
            }
            //kernel::log('dly:'.$_dly['delivery_id'].$delivery['stock_status'].var_dump($status_cfg));
            //更新交易发货状态 API
            if ($delivery['expre_status']=='true' && $delivery['stock_status']=='true' && $delivery['deliv_status']=='true'){
                /*直接校验完成 2012-8-28 刘向峰 start*/
            	kernel::log('dly:___'.$_dly['delivery_id']);
            	$__dly=array("verify"=>"true");
            	$dlyObj->update($__dly, array('delivery_id'=>$_dly['delivery_id']));
            	
            	$dlyItemObj     = &$this->app->model('delivery_items');            	
            	$dlyItemObj->verifyItemsByDeliveryId($_dly['delivery_id']);
            	
            	/*end*/
            	
            	if ($send_flag == true){ 
                    foreach(kernel::servicelist('service.delivery') as $object=>$instance){
                        if(method_exists($instance,'update_status')){
                            $instance->update_status($v['delivery_id'], 'progress');
                        }
                    }
                }
            }

            if ($v['_isMerge_']){//联合打印
                foreach ($v['_log_'] as $key => $val){
                    $opObj->write_log($val, $v['delivery_id'], $v['_memo_'][$key]);
                }
                $dlyObj->updateOrderPrintFinish($v['delivery_id']);
            }else {
                $opObj->write_log($v['_log_'], $v['delivery_id'], $v['_memo_']);
                $dlyObj->updateOrderPrintFinish($v['delivery_id']);
            }
        }

        echo 'true';
    }

    /**
     * 打印备货单
     *
     */
    function toPrintStock(){
        $_err = 'false';
        $ids = $this->processDeliveryId();

		//批次号 by sy
        $idents = $this->_getPrintQueue($ids);
		$idsAll = $this->parsePrintIds($ids);
        $allItems = array();


        $dlyObj = &$this->app->model('delivery');
        $orderObj = &$this->app->model('orders');
        
        $orderIds = array();
        $ids && $orderIds = $dlyObj->getOrderIdByDeliveryId($ids);
        /*$deliveryOrderMap = array();
        $deliveryLen = count($ids);
        for ($i=0; $i<$deliveryLen; $i++) {
            $deliveryOrderMap[$ids[$i]] = $orderIds[$i];
        }*/
        
        $orderList = array();
        foreach ($orderIds as $orderId) {
            $orderList[$orderId] = $orderObj->order_detail($orderId);
        }
        
        $delivery_cost_price = 0;
        $delivery_discount_price = 0;
        foreach ($orderList as $order) {
            $delivery_cost_price += $order['shipping']['cost_shipping'] + $order['shipping']['cost_protect'];
            $delivery_discount_price += $order['discount'];
        }
        
        if ($ids){
            sort($ids);
            $id = array();
            foreach ($ids as $r){
                $dly = $dlyObj->dump($r,'*',array('delivery_items'=>array('*')));
//                foreach ($dly['delivery_items'] as $item){
//                    $re = $dlyObj->existStockIsPlus($item['product_id'],$item['number'],$item['item_id'],$dly['branch_id'],$err,$item['bn']);
//                    if (!$re){
//                        exit($err);
//                    }
//                }
                $id[] = $dly['delivery_id'];
                $this->checkOrderStatus($dly['delivery_id']);

				//批次号
                $allItems[$dly['delivery_id']] = $dly;
            }
            $idstr = implode(',', $id);
            $data  = $dlyObj->countProduct($idstr);//统计商品数量
            /*foreach ($data as $key => $item){
                $bn = $item['bn'];
                $rows = $dlyObj->countProductPos($idstr, $bn);//统计商品在每个货位上的数量
                $data[$key]['pos'] = $rows;
            }*/

            if($ids)$arrPrintStockPrice =$dlyObj->getPrintStockPrice($ids);

            $rows = array();
            if ($ids)
            foreach ($ids as $k => $v){
                $daa = $dlyObj->getProductPosByDeliveryId($v);
                if (!$daa) continue;
                foreach ($daa as $i){
                        $rows[$i['bn']]['bn'] = $i['bn'];
                        $rows[$i['bn']]['name'] = $i['name'];
                        $rows[$i['bn']]['product_name'] = $i['product_name'];
                        $rows[$i['bn']]['store_position'] = $i['store_position'];
                        $rows[$i['bn']]['spec_info'] = $i['spec_info'];
                        $rows[$i['bn']]['num'] += $i['number'];
                        $rows[$i['bn']]['boxs'][] = '<'.($k+1).'('.$i['number'].')>';
                        $rows[$i['bn']]['box'] = implode(',',$rows[$i['bn']]['boxs']);
                        $rows[$i['bn']]['box_price'] = isset($arrPrintStockPrice[$i['bn']]) ? $arrPrintStockPrice[$i['bn']] : 0;
                }
            }
            $memo = $dlyObj->getOrderMemoByDeliveryId($idstr);
        }
//        对usort进行扩展，对多位数组进行值的排序
        function cmp($a, $b){
            return strcmp($a["store_position"], $b["store_position"]);
        }

        usort($rows, "cmp");

		//商品名称和规格取前台,是合并发货单,取第一个订单的货品名称
 	    $status_cfg = $this->app->getConf('ome.delivery.status.cfg');
		$is_print_front = false;
		if($status_cfg && $status_cfg['set']['ome_delivery_is_printstock'] == 1){
			$is_print_front = true;
		}
		if($ids && $is_print_front){
		    $arrPrintProductName = $dlyObj->getPrintProductName($ids);
		    if(!empty($arrPrintProductName)){
    		    foreach($rows as $k=>$v){
    		        $rows[$k]['product_name'] = $arrPrintProductName[$v['bn']]['name'];
                    $rows[$k]['name'] = $arrPrintProductName[$v['bn']]['name'];
                    $rows[$k]['addon'] = $arrPrintProductName[$v['bn']]['addon'];
                    $rows[$k]['spec_info'] = $arrPrintProductName[$v['bn']]['addon'];
    		    }
		    }
		}


        $delivery_total_nums = 0;
        $delivery_total_price = 0;
        foreach($rows as $k=>$v){
            $delivery_total_nums += $v['num'];
            $delivery_total_price += $v['box_price'];
        }
        $this->pagedata['delivery_discount_price'] = $delivery_discount_price;
        $this->pagedata['delivery_total_nums'] = $delivery_total_nums;
        $this->pagedata['delivery_total_price'] = $delivery_total_price + $delivery_discount_price;
        $this->pagedata['picking_list_price'] = $delivery_total_price;
        $this->pagedata['err'] = $_err;


		//批次号
        $this->pagedata['allItems'] = $allItems;
        $this->pagedata['idents'] = $idents['itmes'];
        $this->pagedata['ident'] = $idents['ident'];
        $this->pagedata['errIds'] = $idsAll['errIds'];
        $this->pagedata['errInfo'] = $idsAll['errInfo'];

        $this->pagedata['vid']  = $idstr;
        $this->pagedata['time'] = date("Y-m-d H:i:s");
        $this->pagedata['data'] = $data;
        $this->pagedata['rows'] = $rows;
        $this->pagedata['memo'] = unserialize($memo);
        //$this->pagedata['total'] = $count;
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['title'] = '备货单打印';
        $this->_systmpl = &$this->app->model('print_tmpl_diy');
        $this->_systmpl->singlepage('ome','admin/delivery/stock_print',$this->pagedata);
        $this->display('admin/delivery/print.html');
    }

    /**
     * 录入快递单号
     *
     */
    function insertExpress(){
        if (empty($_POST['id'])){
            exit("请录入快递单号");
        }
        $ids    = $_POST['id'];
        $dlyObj = &$this->app->model('delivery');
        if ($ids)
        foreach ($ids as $k => $i){
            $delivery   = $dlyObj->dump($k);
            $bn = $delivery['delivery_bn'];
            $arr_s      = array('succ', 'cancel', 'back', 'stop');
            if (in_array($delivery['status'], $arr_s) || $delivery['process'] == 'true'){
                exit("发货单".$bn."相关信息不能修改");
            }
            if ($dlyObj->existExpressNo($i, $k)){
                exit("物流单号已存在，发货单为".$bn);
            }
        }
        $opObj = &$this->app->model('operation_log');
        $dlyLogObj = &$this->app->model('delivery_log');
        if ($ids)
        foreach ($ids as $key => $item){
			$dlyLog = array();
            $data['delivery_id'] = $key;
            $data['logi_no']     = $item;

            $dlyObj->save($data);

            if($item && $key){
                $delivery   = $dlyObj->dump($key);
                $dlyLog['delivery_id'] = $key;
                $dlyLog['logi_id']   = $delivery['logi_id'];
                $dlyLog['logi_no']   = $item;
                $dlyLog['logi_name'] = $delivery['logi_name'];
                $dlyLog['create_time'] = time();

                if(!$dlyLogObj->dump(array('delivery_id'=>$key,'logi_no'=>$item))){
                    $dlyLogObj->save($dlyLog);
                }
            }

            $opObj->write_log('delivery_logi_no@ome', $key, '录入快递单');
        }
        $finder_id = $_GET['finder_id'];
        header('content-type:text/html; charset:utf-8');
        echo "<script>";
        echo "alert('快递单号录入成功');";
        echo "opener.finderGroup['".$finder_id."'].refresh.delay(400,opener.finderGroup['".$finder_id."']);";
        echo "window.close();";
        echo "</script>";
        exit;
    }

    /**
     * 合并发货单列表
     *
     * @param bigint $dly_id
     */
    function merge($dly_id){
        $this->begin('index.php?app=ome&ctl=admin_receipts_print');
        if (!isset($dly_id)){
            $this->end(false,'操作出错，请重新操作');
        }
        if ($this->checkOrderStatus($dly_id)) exit("发货单已无法操作，请到订单处理中心处理");
        $Objdly = &$this->app->model('delivery');
        $dly = $Objdly->dump($dly_id);
        $data = $Objdly->getSameKeyList($dly_id);
        $tmp = $data;
        if ($data)
        foreach ($data as $k => $v){
            if ($v['delivery_id'] == $dly_id){
                $tmp_dly = $v;
                unset($tmp[$k]);
            }
        }
        empty($dly['branch_id'])?$branch_id=0:$branch_id=$dly['branch_id'];
        $dly_corpObj = &$this->app->model('dly_corp');
        $braObj = &app::get('ome')->model('branch');

        $this->pagedata['dly_corp'] = $braObj->get_corp($branch_id);
        $this->pagedata['dly'] = $tmp;
        $this->pagedata['olddly'] = $tmp_dly;
        $this->singlepage("admin/delivery/delivery_merge.html");
    }

    /**
     * 拆分发货单列表
     *
     * @param bigint $dly_id
     */
    function split($dly_id){
        $this->begin('index.php?app=ome&ctl=admin_receipts_print');
        if (!isset($dly_id)){
            $this->end(false,'操作出错，请重新操作');
        }
        $Objdly = &$this->app->model('delivery');
        $dly  = $Objdly->dump($dly_id, 'delivery_bn');
        $data = $Objdly->getItemsByParentId($dly_id, 'array', '*');

        $this->pagedata['parent_id'] = $dly_id;
        $this->pagedata['parent_bn'] = $dly['delivery_bn'];
        $this->pagedata['count'] = sizeof($data);
        $this->pagedata['dly'] = $data;
        $this->singlepage("admin/delivery/delivery_split.html");
    }

    /**
     * 合并发货单操作
     *
     */
    function doMerge(){
        $this->begin('index.php?app=ome&ctl=admin_receipts_print&act=merge');
        if (empty($_POST['check']) || sizeof($_POST['check'])<2){
            $this->end(false,'请选择至少两张发货单');
        }
        $checkbox = $_POST['check'];
        $is_bind  = $_POST['is_bind'];
        $order_status = $_POST['order_status'];
        
        if ($checkbox)
        foreach ($checkbox as $item){
            $is_choice['is_bind'][$item] = $is_bind[$item];
        }
        if ($checkbox)
        foreach ($checkbox as $item){
            $is_choice['order_status'][$item] = $order_status[$item];
        }
        if (in_array("ERROR",$is_choice['order_status'])){
            $this->end(false,'您选择的发货单中，某张订单有问题');
        }
        if ($_POST['logi_id'] == ''){
            $this->end(false,'请选择物流公司');
        }
        $ordersObj      = &$this->app->model('orders');
        $Objdly      = &$this->app->model('delivery');
        if ($Objdly->existIsMerge($checkbox)){
            $this->end(false,'选择的发货单中已合并过，请返回列表重新操作');
        }
        
        $order_ids = $Objdly->getOrderIdsByDeliveryIds($checkbox);
        $orders = $ordersObj->getList('order_id, order_bn, status, ship_status, process_status', array('order_id|in' => $order_ids));
        
        foreach ($orders as $os) {
            if($os['status']!='active' || $os['ship_status']!=0 || ($os['process_status']!='splited' && $os['process_status']!='splitting')) {
                $this->end(false,'订单编号'. $os['order_bn'] . '不符合条件');
            }
        }
        
        $Objdly_corp = &$this->app->model('dly_corp');
        $corp        = $Objdly_corp->dump($_POST['logi_id'], 'corp_id,name');

        $delivery['logi_id'] = $corp['corp_id'];
        $delivery['logi_name'] = $corp['name'];

        $result = $Objdly->merge($checkbox, $delivery);
        if ($result){
            $this->end(true,'合并操作已成功','index.php?app=ome&ctl=admin_receipts_print');
        }
        $this->end(false,'合并操作失败');
    }

    /**
     * 拆分发货单操作
     *
     */
    function doSplit(){
        $this->begin('index.php?app=ome&ctl=admin_receipts_print&act=split');
        if (empty($_POST['check'])){
            $this->end(false,'请选择至少一张发货单');
        }
        $Objdly = &$this->app->model('delivery');
        if (($_POST['count'] - sizeof($_POST['check'])) <= 1){
            $result = $Objdly->splitDelivery($_POST['parent_id']);
            if ($result){
                $this->end(true,'拆分操作已成功', 'index.php?app=ome&ctl=admin_receipts_print&act=index');
            }
        }else {
            $result = $Objdly->splitDelivery($_POST['parent_id'], $_POST['check']);
            if ($result){
                $this->end(true,'拆分操作已成功', 'index.php?app=ome&ctl=admin_receipts_print&act=index');
            }
        }
        $this->end(false,'拆分操作失败');
    }

    /**
     * 保存发货单详情信息
     *
     */
    function doDetail(){
        $status = $_POST['status'] ? $_POST['status'] : 0;
        $ctl = $_POST['ctl'];
        $this->begin('index.php?app=ome&ctl='.$ctl.'&act=detail&status='.$status);
        if (empty($_POST['dly'])){
            $this->end(false,'保存失败');
        }
        if ($_POST['dly']['logi_id'] == '' || empty($_POST['dly']['logi_id'])){
            $this->end(false,'请选择物流公司');
        }
        //print_r($_POST['dly']);
        $Objdly     = &$this->app->model('delivery');
        $delivery   = $Objdly->dump($_POST['dly']['delivery_id']);
        //if ($this->checkOrderStatus($delivery['delivery_id'])) exit("发货单已无法操作，请到订单处理中心处理");//判断发货单相应订单是否有问题

        /*$arr_s      = array('succ', 'cancel', 'back', 'stop');
        if (in_array($delivery['status'], $arr_s) || $delivery['process'] == 'true'){
            $this->end(false,'发货单相关信息不能修改');
        }*/
        //物流公司改变 物流单号不改变     将物流单号置空 重新计算物流费用
        $doObj     = &$this->app->model('delivery_order');
        $oObj     = &$this->app->model('orders');
        $Objdly_corp = &$this->app->model('dly_corp');
        $corp        = $Objdly_corp->dump($_POST['dly']['logi_id']);
        $order_id = $doObj->dump(array('delivery_id'=>$_POST['dly']['delivery_id']),'order_id');
        $orders = $oObj->dump(array('order_id'=>$order_id['order_id']),'ship_status');
        if($delivery['logi_id'] != $_POST['dly']['logi_id'] ){
        	if($delivery['logi_no'] == $_POST['dly']['logi_no']){
        		$_POST['dly']['logi_no'] = NULL;
        		$data['logi_no'] = NULL;
        	}else{
        		$data['logi_no'] = $_POST['dly']['logi_no'];
        	}
        	$corp  = $Objdly_corp->dump($_POST['dly']['logi_id']);//物流公司信息
	        //计算预计物流费用
	        $area = $_POST['dly_count'];
	        $arrArea = explode(':', $area);
	        $area_id = $arrArea[2];
	        if (isset($corp['area_fee_conf']) && $corp['area_fee_conf']){
	            $area_fee_conf = unserialize($corp['area_fee_conf']);
	            foreach($area_fee_conf as $k=>$v){
	                 $areas = explode(',',$v['areaGroupId']);

	                 // 再次解析字符
	                  foreach ($areas as &$strArea){
	                    if (strpos($strArea, '|') !== false){
	                       $strArea = substr($strArea, 0, strpos($strArea, '|'));
	                        // 取当前area id对应的最上级的区域id
	                        $objRegions = app::get('ectools')->model('regions');
	                        $arrRegion = $objRegions->dump($area_id);
	                        while ($row = $objRegions->getRegionByParentId($arrRegion['p_region_id'])){
	                             $arrRegion = $row;
	                             $tmp_area_id = $row['region_id'];
	                             if ($tmp_area_id == $strArea){
	                                $area_id = $tmp_area_id;
	                                        break;
	                                    }
	                                }
	                            }
	                        }

	                        if(in_array($area_id,$areas))
	                        {
	                            //如果地区在其中，优先使用地区设置的配送费用，及公式
	                            $corp['firstprice'] = $v['firstprice'];
	                            $corp['continueprice'] = $v['continueprice'];
	                            $corp['dt_expressions'] = $v['dt_expressions'];
	                            break;
	                        }
	                    }
	         }
	        $price = utils::cal_fee($corp['dt_expressions'], $delivery['net_weight'], 0,$corp['firstprice'],$corp['continueprice']); //TODO 生成快递费用
	        $data['delivery_cost_expect'] = $price;

	        if($delivery['logi_id']){
            $dly_corp = $Objdly_corp->dump($_POST['dly']['logi_id']);
            $logi_name = $dly_corp['name'];
            //计算保价费用
            $protect = $dly_corp['protect'];
            if($protect == 'true'){
                $is_protect = 'true';
                $protect_rate = $dly_corp['protect_rate'];//保价费率
                $protect_price = $protect_rate * $delivery['net_weight'];
                $minprice = $dly_corp['minprice'];//最低报价费用
                if($protect_price < $minprice){
                    $cost_protect = $minprice;
                }else{
                    $cost_protect = $protect_price;
                    }
                }
            }
            $data['cost_protect'] = $cost_protect ? $cost_protect:0 ;
            $data['is_protect'] = $is_protect ? $is_protect : 'false';
        }
        if ($_POST['dly']['logi_no'] == ''){
            $_POST['dly']['logi_no'] = NULL;
        }else {
            if ($Objdly->existExpressNo($_POST['dly']['logi_no'], $_POST['dly']['delivery_id'],$order_id)){
                $this->end(false,'已有此物流单号');
            }
        }
        $dly['logi_id']   = $_POST['dly']['logi_id'];
        $dly['logi_no']   = $_POST['dly']['logi_no'];
        $dly['logi_name'] = $corp['name'];
        $dly['memo']      = $_POST['dly']['memo'];

        $result = $Objdly->updateDelivery($dly, array('delivery_id'=>$_POST['dly']['delivery_id']));

        if($_POST['dly']['logi_no'] && $_POST['dly']['delivery_id']){
            $dlyLog['delivery_id'] = $_POST['dly']['delivery_id'];
            $dlyLog['logi_id']   = $_POST['dly']['logi_id'];
            $dlyLog['logi_no']   = $_POST['dly']['logi_no'];
            $dlyLog['logi_name'] = $corp['name'];
            $dlyLog['create_time'] = time();
            $dlyLogObj = &$this->app->model('delivery_log');
            if(!$dlyLogObj->dump(array('delivery_id'=>$dlyLog['delivery_id'],'logi_no'=>$dlyLog['logi_no']))){
                $dlyLogObj->save($dlyLog);
            }
        }
        //物流单号 或是 物流公司改变的时候 判断发货状态
        if($delivery['logi_id'] != $_POST['dly']['logi_id'] || (!empty($delivery['logi_no']) &&  $delivery['logi_no'] != $_POST['dly']['logi_no']) ){
            //未发货的发货单变更物流单号应重新打印快递单
            if($delivery['process'] == 'false'){
                $msg = '物流信息已改变，您应该从新打印快递单';
            }
        }
        $data['net_weight'] = $delivery['net_weight'];
        $data['delivery_id'] = $_POST['dly']['delivery_id'];
        $Objdly->save($data);
        if ($result){
            if ($result === 1){// 是否修改发货单状态信息 (不修改)
                $opObj = &$this->app->model('operation_log');
                $opObj->write_log('delivery_modify@ome', $_POST['dly']['delivery_id'], '修改发货单详情');
            }
            $this->end(true,'保存成功'.$msg,'index.php?app=ome&ctl='.$ctl.'&status='.$status);
        }
        $this->end(false,'保存失败');
    }

    /**
     * 保存货品货位详情信息
     *
     */
    function doItemDetail(){
        //$this->begin('index.php?app=ome&ctl=admin_receipts_print');
        $this->begin();
        if (empty($_POST['num']) || empty($_POST['pos'])){
            $this->end(false,'请填写数量');
        }
        $dly_id     = $_POST['delivery_id'];
        $number     = $_POST['num'];
        $pos        = $_POST['pos'];
        $Objdly     = &$this->app->model('delivery');
        $delivery   = $Objdly->dump($dly_id);
        $arr_s      = array('succ', 'cancel', 'back', 'stop');
        if (in_array($delivery['status'], $arr_s) || $delivery['process'] == 'true'){
            $this->end(false,'发货单相关信息不能修改');
        }
        if ($number)
        foreach ($number as $key => $item){
            $count = $item;
            foreach ($pos[$key] as $k => $i){
                $total += $i;
            }
            if ($total != $count){
                $this->end(false,'保存失败，填写总数不正确');
            }
            $count = 0;
            $total = 0;
        }

        $Objpos = &$this->app->model('dly_items_pos');
        if ($pos)
        foreach ($pos as $id => $row){
            $Objpos->delete(array('item_id'=>$id));//更新前先做删除
        }
        //插入货品货位
        if ($pos)
        foreach ($pos as $key => $item){
            foreach ($item as $k => $i){
                if ($i <= 0){
                    continue;
                }
                $data['item_id']  = $key;
                $data['num']      = $i;
                $data['pos_id']   = $k;
                $Objpos->save($data);
                $data = '';
            }
        }
        $opObj = &$this->app->model('operation_log');
        $opObj->write_log('delivery_position@ome', $_POST['delivery_id'], '发货单货位录入');
        $this->end(true,'保存成功','index.php?app=ome&ctl=admin_receipts_print&act=index');
    }

	/**
     * 打印页面初始化 获取打印批次号
     *
     * @return Array
     */
    function _getPrintQueue($ids) {
        if(!$this->_checkPrintQueue($ids,$msg)){
			$this->message($msg);
			exit;
		}
	    $queueObj = kernel::single('ome_queue');
        $queue = $queueObj->fetchPrintQueue($ids);
        return $queue;
    }

	/**
     * 检查是否能同批次打印
     *
     * @return bool
     */
	function _checkPrintQueue($ids,&$msg) {
        if (!empty($ids))
            sort($ids);

        $delivery_status_cfg = &app::get('ome')->getConf('ome.delivery.status.cfg');//批量打印数量
		$batch_print_nums = $delivery_status_cfg['set']['ome_batch_print_nums'];
        $batch_print_nums = $batch_print_nums ? $batch_print_nums : 100;
        if (count($ids) > $batch_print_nums){
            $msg = "所选发货单号数量已超过批量打印数量 (".$batch_print_nums.")！";
            return false;
        }

        $delivery_check_ident = &app::get('ome')->getConf('ome.delivery.check_ident');
        $delivery_check_ident = $delivery_check_ident ? $delivery_check_ident : 'on';
        
        if($delivery_check_ident == 'on'){
	        $queueObj = kernel::single('ome_queue');
	        if ($queueObj->isExistsQueueItems($ids,$existsQueueItems)) {
	            if(count($ids) != count($existsQueueItems)){
	                $msg = "已生成批次号的发货单不能和未生成的发货单一起打印！";
	            }else{
	                $error = '';
	                foreach($existsQueueItems as $k=>$v){
	                    //$error .= '发货单号:'.$k.' 批次号:'.$v.'<br />';
	                    $error .= '批次号:'.$v.'<br />';
	                }
	                $msg = "以下发货单号已存在不相同的批次号！<br />".$error;
	            }
	            return false;
	        }
        }

        return true;
    }

	/**
     * 添加打印批次号
     *
     * @return Array
     */
    /*function _fetchPrintQueue($ids,&$msg) {
        if (!empty($ids))
            sort($ids);

        $batch_print_nums = &app::get('ome')->getConf('ome.batch_print_nums');//批量打印数量
        $batch_print_nums = $batch_print_nums ? $batch_print_nums : 0;
        if (count($ids) > $batch_print_nums){
            $msg = "所选发货单号数量已超过批量打印数量 (".$batch_print_nums.")！";
            return false;
        }

        $queueObj = kernel::single('ome_queue');
        if ($queueObj->isExistsQueueItems($ids,$existsQueueItems)) {
            if(count($ids) != count($existsQueueItems)){
                $msg = "已生成批次号的发货单不能和未生成的发货单一起打印！";
            }else{
                $error = '';
                foreach($existsQueueItems as $k=>$v){
                    //$error .= '发货单号:'.$k.' 批次号:'.$v.'<br />';
                    $error .= '批次号:'.$v.'<br />';
                }
                $msg = "以下发货单号已存在不相同的批次号！<br />".$error;
            }
            return false;
        }
        $queue = $queueObj->addPrintQueue($ids);
        return $queue;
    }*/

	function message($msg) {

        $this->pagedata['err'] = 'true';
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['time'] = date("Y-m-d H:i:s");
        $this->pagedata['msg'] = $msg;
        $this->singlepage('admin/delivery/message.html');
        $this->display('admin/delivery/print.html');
    }

	function parsePrintIds($ids) {

        $result = array(
            'ids' => array(), //可用于打印的ID
            'errIds' => array(), //不能胜于打印的数据
            'errInfo' => array(), //所有错误信息
        );



        $dlyObj = & app::get('ome')->model('delivery');
        foreach ($ids as $id) {

            $hasError = false;
            //检查当前订单的状态是不是可以打印
            if (!$this->checkOrderStatusEx($id, $errMsg)) {
                //状态有问题的订单是肯定不要打印的
                $result['errIds'][] = $id;
                $result['errInfo'][$id] = $errMsg;
                $hasError = true;
            } else {

                $result['ids'][] = $id;
            }
            if (!$hasError) {
                //检查库存
                $dly = $dlyObj->dump($id, '*', array('delivery_items' => array('*')));
                foreach ($dly['delivery_items'] as $item) {
                    $re = $dlyObj->existStockIsPlus($item['product_id'], $item['number'], $item['item_id'], $dly['branch_id'], $err, $item['bn']);
                    if (!$re) {
                        $result['errIds'][] = $id;
                        $result['errInfo'][$id] .= $err . "&nbsp;,&nbsp;";
                        $hasError = true;
                    }
                }
                //库存有问题的单据认为是要打印的
                if (!in_array($id, $result['ids']))
                    $result['ids'][] = $id;
            }
        }

        if (empty($result['ids'])) {
            if (!empty($result['errIds'])) {

                $msg = sprintf("你所选择的 %d 张单据状态异常，无法打印，本次操作中止！", count($result['errIds']));
            } else {

                $msg = '你没有选择要打印的单据，请重新选择后再试！';
            }
            $this->message($msg);
            exit;
        }

        return $result;
    }

	/**
     * 检查发货单是否可操作
     *
     * @param Integer $dly_id
     * @param String $errMsg  引用，用于返回错误信息
     * @return Boolean
     */
    function checkOrderStatusEx($dly_id, &$errMsg) {
        $Objdly = &app::get('ome')->model('delivery');
        $delivery = $Objdly->dump($dly_id);

        //检查发货单状态，如是合并而成的发货单位
        if (!$Objdly->existOrderStatus($dly_id, $delivery['is_bind'])) {

            $errMsg = "发货单已无法操作，请到订单处理中心处理";
            return false;
        }
        if (!$Objdly->existOrderPause($dly_id, $delivery['is_bind'])) {
            $errMsg = "发货单相关订单已暂停，请到订单处理中心处理";
            return false;
        }

        return true;
    }

    /**
     * 判断发货单号状态是否处于取消或异常或超时或失败或disabled
     *
     * @param bigint $dly_id
     * @return null
     */
    function checkOrderStatus($dly_id){
        $Objdly = &$this->app->model('delivery');
        $delivery = $Objdly->dump($dly_id);
        if (!$Objdly->existOrderStatus($dly_id, $delivery['is_bind'])){
            //echo "发货单已无法操作，请到订单处理中心处理";
            //exit("<script>parent.MessageBox.error('发货单已无法操作，请到订单处理中心处理!');</script>");
            return true;
        }
        if (!$Objdly->existOrderPause($dly_id, $delivery['is_bind'])){
            //echo "发货单相关订单已暂停，请到订单处理中心处理";
            //exit("<script>parent.MessageBox.error('发货单相关订单已暂停，请到订单处理中心处理!');</script>");
            return true;
        }
        return false;
    }

    /**
     * 设置订单样式
     * @param null
     * @return null
     */
    public function showPrintStyle()
    {
        $this->path[] = array('text'=>app::get('ome')->_('订单打印格式设置'));
        $dbTmpl = $this->app->model('print_tmpl_diy');
        $stockPrintTxt = $dbTmpl->get('ome','/admin/delivery/stock_print');
        $deliveryPrintTxt = $dbTmpl->get('ome','/admin/delivery/delivery_print');
        $mergePrintTxt = $dbTmpl->get('ome','/admin/delivery/merge_print');
        $contentPurchase = $dbTmpl->get('purchase','/admin/purchase/purchase_print');
        $contentPurchaseEo = $dbTmpl->get('purchase','/admin/eo/eo_print');
        $contentPurchaseReturn = $dbTmpl->get('purchase','/admin/returned/return_print');

        $this->pagedata['styleContent'] = $stockPrintTxt;
        $this->pagedata['styleContentDelivery'] = $deliveryPrintTxt;
        $this->pagedata['styleContentMerge'] = $mergePrintTxt;
        $this->pagedata['styleContentPurchase'] = $contentPurchase;
        $this->pagedata['styleContentPurchaseEo'] = $contentPurchaseEo;
        $this->pagedata['styleContentPurchaseReturn'] = $contentPurchaseReturn;
        $this->page('admin/delivery/printstyle.html');
    }

    /**
     * 保存订单打印样式
     * @param null
     * @return null
     */
    public function savePrintStyle()
    {
        //$this->begin('index.php?app=ome&ctl=admin_receipts_print&act=showPrintStyle');
        $current_print = $_POST['current_print'];
        $dbTmpl = $this->app->model('print_tmpl_diy');
         switch($current_print){
            case 'txtContent':
                $dbTmpl->set('ome','/admin/delivery/stock_print', $_POST["txtContent"]);
                break;
            case 'txtContentDelivery':
                $dbTmpl->set('ome','/admin/delivery/delivery_print', $_POST["txtContentDelivery"]);
                break;
            case 'txtContentMerge':
                $dbTmpl->set('ome','/admin/delivery/merge_print', $_POST["txtContentMerge"]);
                break;
            case 'txtContentPurchase':
                $dbTmpl->set('purchase','/admin/purchase/purchase_print', $_POST["txtContentPurchase"]);
                break;
            case 'txtContentPurchaseEo':
                $dbTmpl->set('purchase','/admin/eo/eo_print', $_POST["txtContentPurchaseEo"]);
                break;
            case 'txtContentPurchaseReturn':
                $dbTmpl->set('purchase','/admin/returned/return_print', $_POST["txtContentPurchaseReturn"]);
                break;

        }

        echo "<script>$$('.dialog').getLast().retrieve('instance').close();</script>";
        //$this->end($dbTmpl->set('ome','/admin/delivery/merge_print', $_POST["txtContentMerge"]),app::get('ome')->_('订单打印模板保存成功'));
    }

    /**
     * rebackPrintStyle
     *
     * @access public
     * @return void
     */
    public function rebackPrintStyle(){
        //$this->begin('index.php?app=ome&ctl=admin_receipts_print&act=showPrintStyle');
        $current_print = $_POST['current_print'];
        $dbTmpl = $this->app->model('print_tmpl_diy');
        switch($current_print){
            case 'txtContent':
                $dbTmpl->clear('ome','/admin/delivery/stock_print');
                break;
            case 'txtContentDelivery':
                $dbTmpl->clear('ome','/admin/delivery/delivery_print');
                break;
            case 'txtContentMerge':
                $dbTmpl->clear('ome','/admin/delivery/merge_print');
                break;
            case 'txtContentPurchase':
                $dbTmpl->clear('purchase','/admin/purchase/purchase_print');
                break;
            case 'txtContentPurchaseEo':
                $dbTmpl->clear('purchase','/admin/eo/eo_print');
                break;
            case 'txtContentPurchaseReturn':
                $dbTmpl->clear('purchase','/admin/returned/return_print');
                break;
        }

        echo "<script>$$('.dialog').getLast().retrieve('instance').close();</script>";
        //$this->end($dbTmpl->clear('/admin/delivery/merge_print'),app::get('ome')->_('恢复默认值成功'));
    }

}